package cn.tedu.tmall.basic.service.impl;

import cn.tedu.tmall.basic.dao.cache.IDistrictCacheRepository;
import cn.tedu.tmall.basic.dao.persist.repository.IDistrictRepository;
import cn.tedu.tmall.basic.pojo.vo.DistrictCacheVO;
import cn.tedu.tmall.basic.service.IDistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DistrictServiceImpl implements IDistrictService {

    @Autowired
    private IDistrictRepository districtRepository;
    @Autowired
    private IDistrictCacheRepository districtCacheRepository;

    @Override
    public List<DistrictCacheVO> listByParent(Long parentId) {
        // return districtRepository.listByParent(parentId);
        return districtCacheRepository.listByParent(parentId);
    }

    @Override
    public void rebuildCache() {
        districtCacheRepository.deleteAll();

        Long parentId = 0L;
        List<DistrictCacheVO> list = districtRepository.listByParent(parentId);
        System.out.println("查找parentId=0的行政单位列表");
        districtCacheRepository.saveListByParent(parentId, list);
        callRecursion(list);
    }

    private void callRecursion(List<DistrictCacheVO> list) {
        if (!list.isEmpty()) {
            for (DistrictCacheVO district : list) {
                Long id = district.getId();
                System.out.println("查找parentId=" + id + "(" + district.getName() + ")的行政单位列表");
                List<DistrictCacheVO> subList = districtRepository.listByParent(id);
                if (!subList.isEmpty()) {
                    districtCacheRepository.saveListByParent(id, subList);
                    callRecursion(subList);
                }
            }
        }
    }

}
